/*
 * @Descripttion: 
 * @Author: yuxi
 * @Date: 2024-03-04 18:14:28
 * @LastEditors: yuxi
 * @LastEditTime: 2024-03-07 22:38:00
 */ 
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { 
  const {action} = request 
  console.log('action ', action)
  switch (action) {
    case "getAllResult":
      var savedCount = request.savedCount
      console.log('savedCOunt', savedCount)
      // return
      var page = Math.floor(savedCount/20)
      showMask();
      getAllResult(request.uid,  "", [], 1, savedCount, (result) => {
        console.log('result is',result)
        console.log('result.total > result.records.length + savedCount', result.total > result.records.length + savedCount)
        if(savedCount>result.total) {
          result.records = []
        } else {
          while(result.total < result.records.length + savedCount) {
            result.records.pop()
          } 
        }
      
        console.log('result is', result, "savedCount", savedCount)
        removeMask()
        sendResponse(result)
      }) 
    break;
    default:
      break;

  }
   
  return true;
}); 
function removeMask() {
  let mask = document.getElementById('luogu_mask')
  mask && mask.remove()
}
function showMask () {
  let mask = document.createElement('div')
  mask.style.position = "fixed"
  mask.style.left = 0
  mask.style.right = 0
  mask.style.top = 0
  mask.style.bottom = 0
  mask.style.zIndex= 1000
  mask.style.textAlign="center"
  mask.style.fontSize="24px"
  mask.style.color = "white"
  mask.style.display="flex"
  mask.style.alignItems="center"
  mask.style.justifyContent="center"
  mask.id = "luogu_mask"
  mask.innerText = "加载洛谷数据中，请稍后..."
  mask.style.backgroundColor = "rgba(0,0,0,0.4)"
  document.body.appendChild(mask)
}
function getAllResult(uid, pid="", records=[], page=1,savedCount, callback) {  
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
      // 通信成功时，状态值为4
      if (xhr.readyState === 4){
        if (xhr.status === 200){
          let res = JSON.parse(xhr.responseText)
          records = records.concat(res.currentData.records.result) 
          if(res.currentData.records.count > records.length + savedCount) {
            getAllResult(uid, pid, records, page+1, savedCount, callback) 
          } else {
            callback({records, total: res.currentData.records.count})
          }
          
        } else {
          console.error(xhr.statusText);
        }
      }
    };
    xhr.onerror = function (e) {
      console.error(xhr.statusText);
    };
    xhr.open('GET', `https://www.luogu.com.cn/record/list?user=${uid}&page=${page}&language=&orderBy=0&pid=${pid}&_contentOnly=1t`, true);
    xhr.send(null);
}

console.log("content")
